package com.zhm.demo;

import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSONObject;
import com.hthium.device.protocol.IotDataUniProtocol;
import com.zhm.demo.bean.DeviceDataInsertWrapper;
import com.zhm.demo.postgresql.entity.IotUniDataLog;
import com.zhm.demo.postgresql.mapper.IotUniDataLogMapper;
import com.zhm.demo.rockmq.RockMqConfig;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@Slf4j
@Component
public class TestComponent {

    @Autowired
    private IotUniDataLogMapper iotUniDataLogMapper;

    private String makeId(String sn, long ts) {
        return DigestUtils.md5DigestAsHex(sn.getBytes()) + ":" + (sn.length() > 5 ? sn.substring(sn.length() - 5) : sn) + ":" + ts;
    }

    @PostConstruct
    public void init() throws InterruptedException, MQClientException {


        RockMqConfig.Item pre = RockMqConfig.pre();
        //1.创建消费者Consumer，制定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("test-group");
        //2.指定Nameserver地址
        consumer.setNamesrvAddr(pre.getServerAddr());
        // 设置消费模式为集群模式，默认就是集群模式，这里显式设置
        consumer.setMessageModel(MessageModel.CLUSTERING);

        //4.设置回调函数，处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            //接受消息内容
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
//                try {
                    for (MessageExt messageExt : msgs) {
                        log.info("{} {} {}", messageExt.getTopic(), messageExt.getTags(), new String(messageExt.getBody()));
                        String str = new String(messageExt.getBody());
                        log.debug("onMsg {}", str);
                        DeviceDataInsertWrapper deviceDataInsertWrapper = JSONObject.parseObject(str, DeviceDataInsertWrapper.class);
                        if (deviceDataInsertWrapper.getClassName().equals(IotDataUniProtocol.class.toString())) {
                            IotDataUniProtocol iotDataUniProtocol = JSONObject.parseObject(deviceDataInsertWrapper.getContents(), IotDataUniProtocol.class);
                            IotUniDataLog iotUniDataLogDTO = new IotUniDataLog();
                            iotUniDataLogDTO.setId(makeId(iotDataUniProtocol.getSn(), iotDataUniProtocol.getTs()));
                            iotUniDataLogDTO.setTs(iotDataUniProtocol.getTs());
                            iotUniDataLogDTO.setDate(LocalDateTime.ofInstant(Instant.ofEpochMilli(iotUniDataLogDTO.getTs()), ZoneId.systemDefault()));
                            iotUniDataLogDTO.setSn(iotDataUniProtocol.getSn());
                            iotUniDataLogDTO.setAction(iotDataUniProtocol.getAction());
                            iotUniDataLogDTO.setFunc(iotDataUniProtocol.getFunc());
                            iotUniDataLogDTO.setProtocolKey(iotDataUniProtocol.getProtocolKey());
                            iotUniDataLogDTO.setParamMap(iotDataUniProtocol.getParamMap());
                            if (ObjUtil.isNotNull(iotDataUniProtocol.getRaw())) {
                                iotUniDataLogDTO.setContents(iotDataUniProtocol.getRaw().getContents());
                                iotUniDataLogDTO.setContentType(iotDataUniProtocol.getRaw().getContentType());
                                iotUniDataLogDTO.setTopic(iotDataUniProtocol.getRaw().getTopic());
                            }
                            iotUniDataLogMapper.insert(iotUniDataLogDTO);
                        }
                    }
                    // 手动提交 ACK，表示消息消费成功
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
//                } catch (Exception e) {
//                    log.error("",e);
//                    // 消费失败，稍后重试
//                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
//                }
            }
        });


        //3.订阅主题Topic和Tag
        consumer.subscribe("topic_iot_data_log_insert", "*");
        //5.启动消费者consumer
        consumer.start();
    }
}
//
//
//    @Autowired
//    private UploadOriginMapper uploadOriginMapper;
//
//    @Autowired
//    private UploadHistoryMapper uploadHistoryMapper;
//
//    @Autowired
//    private DataFeignClient dataFeignClient;
//
//    @Autowired
//    private CsvMapper csvMapper;
//
//    @Autowired
//    private IDevicesService devicesService;
//
//    @Autowired
//    private PreIotModelMapper preIotModelMapper;
//
//    @Autowired
//    private ProdDevicesMapper prodDevicesMapper;
//
//    @Autowired
//    private HiveDbMapper hiveDbMapper;
//
//    @Autowired
//    private IotUniDataLogRepository iotUniDataLogRepository;
//
//    @Autowired
//    private ElasticsearchTemplate elasticsearchTemplate;
//
//    public List<SearchHit<IotDeviceImage>> fixedArea(Double lat, Double lng, Integer distance) {
//        NativeQueryBuilder nativeQueryBuilder = new NativeQueryBuilder().withQuery(
//                a -> a.bool(
//                        b -> b.filter(
//                                c -> c.geoDistance(
//                                        new GeoDistanceQuery.Builder().location(
//                                                new GeoLocation.Builder().latlon(new LatLonGeoLocation.Builder().lat(lat).lon(lng).build()).build()
//                                        ).distance(distance + "").distanceType(GeoDistanceType.Arc).field("location").build()
//                                )
//                        )
//                )
//        );
//        SearchHits<IotDeviceImage> search = elasticsearchTemplate.search(nativeQueryBuilder.build(), IotDeviceImage.class);
//        return search.getSearchHits();
//    }
//
//    public void testEsImage() {
//        String sn = "123";
//        String id = "xxxxxx" + ":" + sn;
//
//        Optional<IotDeviceImage> byId = iotUniDataLogRepository.findById(id);
//
//        IotDeviceImage iotDeviceImage = new IotDeviceImage();
//        byId.ifPresent(iotDeviceImageDb -> {
//            BeanUtils.copyProperties(iotDeviceImageDb, iotDeviceImage);
//        });
//
//        iotDeviceImage.setId(id);
//        iotDeviceImage.setSn(sn);
//        iotDeviceImage.setTs(System.currentTimeMillis());
//        iotDeviceImage.setDate(new Date());
//
//
//        GeoPoint geoPoint = new GeoPoint(22.5445741, 114.0545429);
//         iotDeviceImage.setLocation(geoPoint);
//         iotDeviceImage.setUserIdList(List.of(13216464L, 878941561L));
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("test2", 13216464L);
//        if (ObjUtil.isNull(iotDeviceImage.getParamMap())) {
//            iotDeviceImage.setParamMap(new HashMap<>());
//        }
//        iotDeviceImage.getParamMap().putAll(map);
//        iotUniDataLogRepository.save(iotDeviceImage);
//
//        log.info("init");
//
//
//        List<IotDeviceImage> tag01 = iotUniDataLogRepository.findByUserIdListIn(List.of(88941561L));
//
//        log.info("init2 {}", tag01);
//
//        List<SearchHit<IotDeviceImage>> searchHits = fixedArea(52.5445841, 114.0545529, 500);
//
//        log.info("init3 {}", searchHits);
//    }
//    @PostConstruct
//    public void init() throws URISyntaxException {
//
//
//        List<Map<String, Object>> maps = hiveDbMapper.listAllDb();
//
//        log.info("{}", maps);

//        List<Devices> devices = prodDevicesMapper.listBySql("select * from iot_devices where timezone !='Asia/Shanghai'");
/// /        System.out.println(devices);
//
//        StringJoiner stringJoiner = new StringJoiner("\r\n");
//        for (Devices device : devices) {
//            stringJoiner.add("HMSET 'IOT:DEVICE:IMAGE_CACHE:"+device.getSnCode()+"' 'timezone' "+"'{\"ts\":1722393701656,\"val\":\"Asia/Shanghai\"}'");
//        }
//
//        String s = stringJoiner.toString();
//        System.out.println(s);
//        System.setProperty("java.awt.headless", "false");
//        StringSelection ss = new StringSelection(s);
//        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//
//        clipboard.setContents(ss, null);


//        HCV2MqttDemoHelper hcv2MqttDemoHelper = new HCV2MqttDemoHelper();
//        hcv2MqttDemoHelper.userLogin("")

//        List<IotModel> iotModels = iotModelMapper.listAll();
//        System.out.println(iotModels);

//        LambdaQueryWrapper<Devices> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.last("LIMIT 1");
//        List<Devices> list = devicesService.list(queryWrapper);
//        System.out.println(list);

//        List<Map<String, String>> maps = csvMapper.selectAll();
//        System.out.println(maps);

//        List<UploadOrigin> uploadOrigins = uploadOriginMapper.selectList("24357029320240308", 100, System.currentTimeMillis() - (8 * 60 * 60 * 1000), System.currentTimeMillis());
//        uploadOrigins.forEach(uploadOrigin -> {
//            String str = HexUtil.decodeHexStr(uploadOrigin.getRawStr());
//            log.info(str);
//        });
//        System.out.println(uploadOrigins.size());


//        List<UploadHistory> uploadHistories = uploadHistoryMapper.selectList("24357029320240308", 100, System.currentTimeMillis() - (8 * 60 * 60 * 1000), System.currentTimeMillis());
//        uploadHistories.forEach(uploadHistory -> {
//            log.info(uploadHistory.getDataMap());
//        });
//        System.out.println(uploadHistories.size());


//        TestReq testReq = new TestReq();
//        testReq.setA("a");
//        String add = dataFeignClient.add(testReq);
//        System.out.println(add);


//
//        new Thread(()->{
//            try {
//                Thread.sleep(50000);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity("http://data/data/test", testReq, String.class);
//            System.out.println(stringResponseEntity.getBody());
//        }).start();
//
//
//    }

